#ifndef FAVICONGRABBER_H
#define FAVICONGRABBER_H

#include <QObject>

#include <QPixmap>
#include <QIcon>
#include <QUrl>
#include <QString>
#include <QMap>

class QWebPage;

class QNetworkReply;
class QNetworkAccessManager;

class FavIconGrabber : public QObject
{
    Q_OBJECT

public:

    static FavIconGrabber *grab(const QUrl &url);
    virtual ~FavIconGrabber();

    void start();

signals:

    void grabSucceeded(QIcon &icon);
    void grabFailed(QIcon &icon);

protected:

    explicit FavIconGrabber(const QUrl &url);

    void cache();

    void succeeded();
    void failed();

    const bool loadFromCache();
    const bool loadFromFile();


    void startAsyncParse();

    void checkAndActIfFuckedUp();

    void asyncGetWebPage();
    void directAsyncGrab();

    void asyncGetPixmap(const QString &href);


    static const QString fileName(const QUrl &url);
    static const QString parsePageIconHRef(QWebPage *page);

protected slots:

    void me_getWebPage_succeeded(bool ok);
    void me_getWebPage_failed();

    void me_getBytes_succeeded(QNetworkReply *reply);
    void me_getBytes_failed();


protected:
    static QMap<QString, QIcon> m_cache;

    const QUrl m_url;

    QIcon m_icon;

    uint m_asyncGetPixmapFails;

    QWebPage *m_page;
    QNetworkAccessManager *m_networkAccessManager;
};

#endif // FAVICON_H
